<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { Delete } from '@element-plus/icons-vue'
import { formatTime } from '@/utils/format'
import {
  getReviewService,
  getReviewImgService,
  getCommentService,
  delCommentService,
  delReviewImgService,
  delReviewService,
} from '@/api/comment'
import { getUserNameService } from '@/api/order'

const reviewList = ref([])
const NameList = ref([])
const loading = ref(false)
const total = ref(null)
const photos = ref([])
const comments = ref([])

const getReview = async () => {
  loading.value = true
  const res = await getReviewService()
  console.log(res.data.data)
  reviewList.value = res.data.data
  total.value = res.data.data.length
  loading.value = false
  await updateNameList()
}
// 获取用户名的异步函数
const getUserName = async (userId) => {
  // 否则发起异步请求获取用户名
  const res = await getUserNameService(userId)
  return res.data.data[0].full_name
}
const getReviewImg = async (order_id) => {
  const res = await getReviewImgService(order_id)
  return res.data.data
}
const getComment = async (order_id) => {
  const res = await getCommentService(order_id)
  return res.data.data
}

// 使用 watch 来监听 orderList 的变化，确保 NameList 数据更新完毕后才渲染
watch(reviewList, async (newReviewList) => {
  if (newReviewList.length > 0) {
    await updateNameList() // 数据更新完毕后更新 NameList
  }
})
// 更新 NameList 的函数
const updateNameList = async () => {
  NameList.value = []
  photos.value = []
  comments.value = []

  for (let i = 0; i < reviewList.value.length; i++) {
    const userId = reviewList.value[i].user_id
    const orderId = reviewList.value[i].order_id
    const userName = await getUserName(userId) // 获取用户名
    const photo = await getReviewImg(orderId)
    const comment = await getComment(orderId)

    // 更新 NameList
    const res = NameList.value.find((r) => r.order_id === orderId)
    if (!res) {
      NameList.value.push({
        order_id: orderId,
        user_name: userName,
      })
      photos.value.push(photo)
      comments.value.push(comment)
    }
  }
  console.log('NameList', NameList.value)
  console.log('photos', photos.value)
  console.log('comments', comments.value)
}

// 根据 orderId 查找对应的 user_name
const fff = (orderId) => {
  const res = NameList.value.find((r) => r.order_id === orderId)
  return res ? res.user_name : '未知' // 如果找不到用户姓名，返回 '未知'
}
const ggg = (orderId) => {
  return photos.value.find((r) => r[0].order_id === orderId)
}
const hhh = (orderId) => {
  return comments.value.find((r) => r[0].order_id === orderId)
}

onMounted(() => {
  getReview()
})

// 删除房间列表信息
const onDelChannel = async (row) => {
  await ElMessageBox.confirm('你确认删除该条数据吗？', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })
  await delCommentService(row.order_id)
  await delReviewImgService(row.order_id)
  await delReviewService(row.order_id)
  ElMessage({ type: 'success', message: '删除成功' })
  getReview()
}
//分页
const currentPage = ref(1) // 当前页
const pagesize = ref(3) // 每页条数
// pagesize每页条数 改变时触发
const onSizeChange = (size) => {
  currentPage.value = 1
  pagesize.value = size
}
// 分页数据计算属性
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pagesize.value
  const end = start + pagesize.value
  return reviewList.value.slice(start, end)
})

// currentPage 当前页 改变时触发
const onCurrentChange = (page) => {
  currentPage.value = page
}
</script>
<template>
  <page-container title="评论管理">
    <div>
      <el-table :data="paginatedData" v-loading="loading" style="width: 100%; margin-top: 20px">
        <el-table-column label="序号" align="center" width="80">
          <template #default="{ $index }">
            <!-- 当前页的索引加上偏移量来计算序号 -->
            {{ $index + 1 + (currentPage - 1) * pagesize }}
          </template>
        </el-table-column>
        <el-table-column
          label="评价ID"
          prop="review_id"
          align="center"
          width="80"
        ></el-table-column>
        <el-table-column label="订单ID" prop="order_id" align="center" width="80"></el-table-column>
        <el-table-column label="顾客" align="center" width="80">
          <template #default="{ row }">
            {{ fff(row.order_id) }}
          </template>
        </el-table-column>
        <el-table-column label="房间名称" prop="room_name" align="center"></el-table-column>
        <el-table-column
          label="评语"
          prop="comment"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="点赞数" prop="likes" align="center" width="80"></el-table-column>
        <!-- 图片列 -->
        <el-table-column label="图片" align="center" width="170">
          <template #default="{ row }">
            <div style="display: flex; flex-wrap: wrap; justify-content: flex-start">
              <el-image
                v-for="(image, index) in ggg(row.order_id)"
                :key="index"
                :src="image.file_url"
                style="
                  width: 65px;
                  height: 45px;
                  margin: 2px;
                  object-fit: cover;
                  border-radius: 2px;
                "
              ></el-image>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="评论" prop="user_id" align="center"></el-table-column> -->
        <!-- 显示多条评论 -->
        <el-table-column label="评论" align="left">
          <template #default="{ row }">
            <div
              v-for="(comment, index) in Array.isArray(hhh(row.order_id))
                ? hhh(row.order_id).slice(0, 4)
                : []"
              :key="index"
              style="margin-bottom: 8px"
            >
              <span
                style="
                  display: inline-block;
                  width: 130px;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                "
                >{{ comment.comment }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" align="center">
          <template #default="{ row }">
            {{ formatTime(row.review_date) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <!-- row 就是 channelList 的一项，类似于item； $index 下标 -->
          <template #default="{ row }">
            <el-button
              :icon="Delete"
              circle
              plain
              type="danger"
              @click="onDelChannel(row)"
            ></el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="没有数据"></el-empty>
        </template>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pagesize"
        :page-sizes="[2, 3, 4, 5, 10]"
        layout="jumper, total, sizes, prev, pager, next"
        background
        :total="total"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </div>
  </page-container>
</template>
<style lang="scss" scoped>
.el-table {
  margin-top: 20px;
}
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.example-showcase .el-dropdown + .el-dropdown {
  margin-left: 15px;
}
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
</style>
